package org.spring.springboot.view;

import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spring.springboot.domain.Area;
import org.springframework.web.servlet.view.document.AbstractXlsView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 描述：
 * <p>
 *
 * @author: 赵新国
 * @date: 2018/7/2 10:25
 */
public class ExcelView extends AbstractXlsView {

    private static final Logger logger = LoggerFactory.getLogger(ExcelView.class);

    @Override
    protected void buildExcelDocument(Map<String, Object> model, Workbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception {

        long start = System.currentTimeMillis();

        // change the file name
        response.setHeader("Content-Disposition", "attachment; filename=\"my-xls-file.xls\"");

        List<Area> areas = (List<Area>) model.get("areas");

        // create excel xls sheet
        Sheet sheet = workbook.createSheet("Area Detail");
        sheet.setDefaultColumnWidth(30);

        // create style for header cells
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setFontName("Arial");
        style.setFillForegroundColor(HSSFColor.BLUE.index);
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        font.setBold(true);
        font.setColor(HSSFColor.WHITE.index);
        style.setFont(font);


        // create header row
        Row header = sheet.createRow(0);
        header.createCell(0).setCellValue("provinceName");
        header.getCell(0).setCellStyle(style);
        header.createCell(1).setCellValue("cityName");
        header.getCell(1).setCellStyle(style);
        header.createCell(2).setCellValue("areaName");
        header.getCell(2).setCellStyle(style);
        header.createCell(3).setCellValue("areaId");
        header.getCell(3).setCellStyle(style);

        int rowCount = 1;

        for(Area area : areas){
            Row userRow =  sheet.createRow(rowCount++);
            userRow.createCell(0).setCellValue(area.getProvinceName());
            userRow.createCell(1).setCellValue(area.getCityName());
            userRow.createCell(2).setCellValue(area.getAreaName());
            userRow.createCell(3).setCellValue(area.getAreaId());
        }

        long end = System.currentTimeMillis();

        logger.info("导出Excel耗时：" + (end - start) + " 毫秒.");
    }
}
